import React, { useReducer } from 'react';

// 定义一个关于num的reducer
function NumReducer(state, action){
    let newState = JSON.parse(JSON.stringify(state));
    switch (action.type) {
        case 'addNum':
            newState.num += action.value;
            break;
        default:
            break;
    }

    return newState;
}

export default function UseReducerTest(){
    // useReducer:传入手写reducer方法和原始state返回新state和dispatch进行使用
    const [state, dispatch] = useReducer(NumReducer, { num: 0});

    return (
        <div>
            <div>嘻嘻嘻{state.num}</div>
            <button onClick={ () => dispatch({ type: 'addNum', value: 1 }) } >累加</button>
        </div>
    )
}